<?php 

/**
 * 用户数据库底层操作
 DROP TABLE IF EXISTS `dict_user`;
CREATE TABLE `dict_user` (
  `u_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(20) NOT NULL,
  `email` varchar(30) DEFAULT NULL,
  `status` tinyint(2) DEFAULT NULL,
  `birthday` date DEFAULT '0000-00-00',
  `regtime` datetime DEFAULT NULL,
  `regip` varchar(15) DEFAULT NULL,
  `qq` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`u_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 */
Class UserModel extends Model{

  /**
   * 判断用户名是否存在
   * @param  [type]  $username [description]
   * @return boolean           [description]
   */
  public function isUserExist($username)
  {
    if ($this->where("username= '" . $username . "'")->find()) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 根据用户id获取用户资料
   * @param  int    $u_id [description]
   * @return [type]       [description]
   */
  public function selectUserByUid(int $u_id)
  {
    return $this->where("u_id= '" . $u_id . "'")->find();
  }

  public function selectUsernameByUid(int $u_id)
  {
    return $this->where("u_id= '" . $u_id . "'")->field('username')->find();
  }

  /**
   * 根据用户名获取用户资料
   * @param  [type] $username [description]
   * @return [type]           [description]
   */
  public function selectUserByUsername($username)
  {
    return $this->where("username= '" . $username . "'")->find();
  }

  /**
   * 添加用户
   * @param [type] $data [description]
   * @return 如果数据非法或者查询错误则返回false,
   * 如果是自增主键 则返回主键值，否则返回1
   */
  public function addUser($data)
  {
    // $data['password'] = encode($data['password']);
    return $this->add($data);
  }

  /**
   * 根据用户id删除用户
   * @param  [type] $u_id [description]
   * @return [type]       [description]
   */
  public function delUserByUid($u_id)
  {
    return $this->where('u_id=' . $u_id)->delete();
  }

  /**
   * 更新用户信息
   * @param  [type] $data [description]
   * @return 如果查询错误或者数据非法返回false,
   * 如果更新成功返回影响的记录数
   */
  public function updateUser($data)
  {
    return $this->save($data);
  }

  /**
   * 修改密码
   * 判断用户旧密码是否正确，若正确，则更新密码为新密码
   * @param  [int] $u_id     [用户id]
   * @param  [varchar] $password [用户密码]
   * @return [type]           [description]
   */
  public function changePassword($u_id, $oldPassword, $newPassword)
  {
    if ($this->where('u_id='.$u_id . " and password=" . encode($oldPassword))) {
      $data["u_id"] = $u_id;
      $data["password"] = encode($newPassword);
      return $this->save($data);
    } else {
      return false;
    }
  }
}

 ?>